package com.illtamer.infinite.sillage.entity;

import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class ViewHandler {

    /**
     * key: ipAddr, value: blogId
     * */
    private final HashMap<String, Integer> ipRecords = new HashMap<>();

    public void record(Integer blogId) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(attributes);
        HttpServletRequest request = attributes.getRequest();
        ipRecords.put(request.getRemoteAddr(), blogId);
    }

    /**
     * @return key: blogId, value: count
     * */
    public Map<Integer, Long> analysis() {
        Map<Integer, Long> result = ipRecords.entrySet().stream()
                .collect(Collectors.groupingBy(
                        Map.Entry::getValue, Collectors.counting()
                ));
        ipRecords.clear();
        return result;
    }

}
